const autorBooks = document.querySelector('.autor-books')
const likebooks = document.querySelector('.likebooks')
const typeRank = document.getElementById('typeRank')
const shopping = document.getElementById('shopping')
const comments =document.querySelector('.comment-box')
const recommendTicket = document.querySelector('.recommendTicket-rect-new')
const catalogList = document.querySelector('.catalog-list')
const nav1 = document.querySelector('.nav-1')
const nav2 = document.querySelector('.nav-2')
const nav3 = document.querySelector('.nav-3')
const currentNav = document.querySelector('.current-nav-1')
console.log("原始 search：", location.search);
const jsonStr = location.search.slice(1); 


const decodedStr = decodeURIComponent(jsonStr); 
const bookData = JSON.parse(decodedStr); 
console.log(bookData);
let num = 1

//渲染作者的其他作品
fetch('https://www.iceread.com/api/story/otherbook/page?id=1015717&cb=1756119541258').then(res=> res.json()).then(res1=> {
    res1.authorOtherStory.forEach((item) => {
        autorBooks.innerHTML+=`
            <div>
                <a href="channelDetail.html?id=${item.id}">
                    <img src="${item.cover}" alt="">
                    <span>${item.name}</span>
                </a>
            </div>
        `
    });
}).catch(err=> {
    console.log(err);
})
//渲染猜你喜欢
const a=()=> {
        return fetch('https://www.iceread.com/api/story/typeRecommend?size=6&type=%E7%8E%B0%E4%BB%A3%E8%A8%80%E6%83%85&targetName=%E5%9D%90%E8%90%BD%E5%B1%8B%E9%A1%B6%E4%B8%8A%E7%9A%84%E6%B8%A1%E9%B8%A6&cb=1756120333556').then(res=> res.json()).then(res1=> {
        res1.typeRecommend.forEach((item,index)=> {
                likebooks.innerHTML+=`
                <div class="${index==0?'on':'like-book'}" onmouseenter="changeclass(event)">
                    <div class="a" onclick='jumpss(${JSON.stringify(item.story)})'>
                        <em class="num">0${index+1}</em>
                        <img src="${item.story.cover}" alt="">
                        <span class="bookName">${item.story.name}</span>
                        <span class="author">${item.story.author}</span>
                    </div>
                </div>
            `
        })
    }).catch(err=> {
        console.log(err);
    })
}
//渲染月票榜
const b=()=> {
    return fetch('https://www.iceread.com/api/common/rank/6264/3/5?cb=1756121750679').then(res=> res.json()).then(res1=> {
    res1.list.forEach((item,index)=> {
        typeRank.innerHTML+=`
            <div class="${index==0?'on1':'like-book1'}" onmouseenter="changeclass1(event)">
                 <div class="a" onclick='jumpss(${JSON.stringify(item.story)})'>
                    <em class="num">0${index+1}</em>
                    <img src="${item.story.cover}" alt="">
                    <span class="bookName">${item.story.name}</span>
                    <span class="author">${item.story.author}</span>
                </div>
            </div>
        `
    })
}).catch(err=> {
    console.log(err);
})
}
//渲染销量榜
const c = () => {
    return fetch('https://www.iceread.com/api/common/rank/6274/0/5?cb=1756121750680').then(res=> res.json()).then(res1=> {
    res1.list.forEach((item,index)=> {
        shopping.innerHTML+=`
            <div class="${index==0?'on2':'like-book2'}" onmouseenter="changeclass2(event)" onmouse>
                 <div class="a"  onclick='jumpss(${JSON.stringify(item.story)})'>
                    <em class="num">0${index+1}</em>
                    <img src="${item.story.cover}" alt="">
                    <span class="bookName">${item.story.name}</span>
                    <span class="author">${item.story.author}</span>
                </div>
            </div>
        `
    })
}).catch(err=> {
    console.log(err);
})
}
function jumpss(hrefs){
    location.href=`./channelDetail.html?${JSON.stringify(hrefs)}`
}
//鼠标经过书籍改变类名及其样式
const changeclass = (event) => { 

    const currentElement = event.target.closest('.like-book, .on');
    if (!currentElement) return; 

    if (currentElement.classList.contains('on')) {
        return;
    }

    const allOnElements = document.querySelectorAll('.on');
    allOnElements.forEach((item) => {
        item.classList.remove('on');
        item.classList.add('like-book');
    });
    currentElement.classList.remove('like-book');
    currentElement.classList.add('on');
}
const changeclass1 = (event) => { 
    //获取类名为like-book1和on1的标签
    const currentElement = event.target.closest('.like-book1, .on1');
    console.log(currentElement);
    
    if (!currentElement) return; 
    //检查contains是否有类名on1
    if (currentElement.classList.contains('on1')) {
        return;
    }

    const allOnElements = document.querySelectorAll('.on1');
    allOnElements.forEach((item) => {
        item.classList.remove('on1');
        item.classList.add('like-book1');
    });
    currentElement.classList.remove('like-book1');
    currentElement.classList.add('on1');
}
const changeclass2 = (event) => { 

    const currentElement = event.target.closest('.like-book2, .on2');
    if (!currentElement) return; 

    if (currentElement.classList.contains('on2')) {
        return;
    }

    const allOnElements = document.querySelectorAll('.on2');
    allOnElements.forEach((item) => {
        item.classList.remove('on2');
        item.classList.add('like-book2');
    });
    currentElement.classList.remove('like-book2');
    currentElement.classList.add('on2');
}
//异步等待
const d =async()=> {
    try {
        await a()
        await b()
        await c()
        changeclass()
        changeclass1()
        changeclass2()
    }catch(err) {
        console.log(err);
        
    }
}
d()
//渲染评论区
const e = (page = 1) => {
    return fetch(`https://www.iceread.com/api/story/comment/page?storyId=1015717&pageNo=${page}&cb=1756187364606`).then(res=> res.json()).then(res1=> {
    console.log(res1.commentPage.list);
    res1.commentPage.list.forEach(item=> {
        comments.innerHTML+=`
            <div class="comment-list">
                <div class="list-tx">
                    <img src="${item.headImage}" alt="">
                </div>
                <div class="dd">
                    <h2><span>${item.nickname}</span></h2>
                    <p class="con-sent">${item.commentBody}</p>
                    <div class="replytime">
                        <p class="senttime">${item.createDateStr}</p>
                        <p class="reply">回复</p>
                    </div>
                </div>
            </div>
        `
    })
    layui.use(function(){
        var laypage = layui.laypage;
        laypage.render({
            elem: 'demo-laypage-theme',
            count: res1.commentPage.total,
            theme: '#ff9ab4',
            curr: num,
            jump: function(obj, first){
                num = obj.curr
                console.log(obj.curr); // 得到当前页，以便向服务端请求对应页的数据。
                console.log(obj.limit); // 得到每页显示的条数
                if(!first){
                    comments.innerHTML=''
                    e(obj.curr)
                }
            }
        });
    });
}).catch(err=> {
    console.log(err);
})
}
e(page = 1)
//渲染推荐票
const f=()=> {
        return fetch('https://www.iceread.com/api/story/monthTicketList?storyId=1015717&cb=1756284297578').then(res=> res.json()).then(res1=> {
        res1.monthTicketList.forEach((item,index)=> {
            recommendTicket.innerHTML+=`
                <li class="recommendTicket-list">
                    <i class="icon"></i>
                    <span>
                        投<em>${item.monthNum}</em>张推荐票
                    </span>
                </li>
            `
        })
    }).catch(err=> {
        console.log(err);
    })
}
f()
//渲染目录
const g=()=> {
    fetch(`https://www.iceread.com/api/story/chapters?volumeId=10019121&cb=1757168331819`).then(res=> res.json()).then(res1=> {
        res1.chapters.slice(0,10)
        res1.chapters.slice(0,10).forEach((item,index)=> {
            catalogList.innerHTML+=`
                <a href="">${item.name}</a>
            `
        })
    }).catch(err=> {
        console.log(err);
    })
}
g()
//点击实现跳转目录当前页面高度
const backmulu = () => {
    window.scrollTo(0, 1100);
    nav2.classList.add('nav');
    nav1.classList.remove('nav');
    nav3.classList.remove('nav');
};
//点击实现跳转简介当前页面高度
const backjianjie=()=>{
    window.scrollTo(0,500)
    nav1.classList.add('nav')
    nav2.classList.remove('nav')
    nav3.classList.remove('nav')
}
//点击实现跳转评论当前页面高度
const backpinglun=()=>{
    window.scrollTo(0,1400)
    nav3.classList.add('nav')
    nav1.classList.remove('nav')
    nav1.classList.remove('nav-1')
    nav2.classList.remove('nav')
}
//滚动监听到哪里哪里的下边框有
const h = () => {
    window.addEventListener('scroll', () => {
        if (500 <= window.scrollY && window.scrollY < 1100) {
            nav1.classList.add('nav');
            nav2.classList.remove('nav');
            nav3.classList.remove('nav');
        } 
        else if (1100 <= window.scrollY && window.scrollY < 1400) {
            nav2.classList.add('nav');
            nav1.classList.remove('nav');
            nav3.classList.remove('nav');
        } 
        else if (window.scrollY >= 1400) {
            nav3.classList.add('nav');
            nav1.classList.remove('nav');
            nav2.classList.remove('nav');
        } 
        else {
            nav1.classList.add('nav');
            nav1.classList.add('nav-1');
            nav2.classList.remove('nav');
            nav3.classList.remove('nav');
        }
    });
};
h()
//鼠标滚动到一定距离改变div的固定定位
const i=()=>{
    window.addEventListener('scroll',()=> {
        if(scrollY>400) {
            currentNav.classList.add('fix')
        }else {
            currentNav.classList.remove('fix')
        }
    })
}
i()
//渲染书籍信息
const bookImg = document.querySelector('.book-img');
const bookContent = document.querySelector('.book-content')
const introduce = document.querySelector('.introduce')
const detailsMainNav = document.querySelector('.details-main-nav')
const girlBg = document.querySelector('.girlBg')
const authorSent = document.querySelector('.author-sent')
const date = new Date(bookData.latestChapterTime);

const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份0-11，补零
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');

const result = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
let savedBooks = JSON.parse(localStorage.getItem('savedBooks'));
let isbookcunzai = savedBooks.some(book => book.id === bookData.id)
bookImg.innerHTML += `
    <a href="">
        <img src="${bookData.cover}" alt="书籍封面">
    </a>
`;
const m =()=> {
    bookContent.innerHTML=''
    bookContent.innerHTML +=`
    <div class="fire-value">
        <div class="fv-count">
            <em>${((bookData.fireValue)/10000).toFixed(1)}</em>
            <span>万</span>
            积分
        </div>
    </div>
    <h1 class="bookName">
    ${bookData.name}
    </h1>
    <span class="autorName">${bookData.author}</span>
    <span class="classify">分类：
        <a href="" target="_blank">${bookData.type}</a>
    </span>
    <span class="lab">
        标签：<a href="" target="_blank">${bookData.tag}</a>
    </span>
    <span class="worNum">
        字数： ${bookData.wordNumber}
    </span>
    <p class="state">
        <span class="end">${bookData.finishTime==1?'连载中':'已完结'}</span>
        <a href="">${bookData.latestChapter}</a>
        <span class="time">${result}</span>
    </p>
    <div class="btn-list">
        <div class="bt">
            <a class="like" href="">立即阅读</a>
            <div class="addbook" href="" onclick="addbook(${bookData.id})">${isbookcunzai?'已入库':'加入书架'}</div>
        </div>
        <div class="tool">
            <div class="twoCode">
                <div class="tCBox">
                    <img src="https://c.hotread.com/girlPc/assets/images/qrcode-girl.png" alt="">
                </div>
            </div>
            <div class="transpond">
                <div class="white-box">
                    <div class="tcbox">
                    <img src="https://c.hotread.com/girlPc/assets/images/qrcode-girl.png" alt="">
                    </div>
                </div>
            </div>
        </div>
    </div>
`
}
m()
introduce.innerHTML +=`
    <p>${bookData.introduce}</p>
`
detailsMainNav.innerHTML +=`
    <a class="right-arrows" href="">首页</a>
    <a class="right-arrows" href="">现代言情</a>
    <a class="bookname" href="">${bookData.name}</a>
`
girlBg.innerHTML +=`     
    <div class="author-tx">
        <img src="https://p0.duyao001.com/image/common/3c9497684f37bbccd36f541550b942f3.png" alt="">
    </div>
    <p class="author-name">${bookData.author}</p>
`

const searchState = {
    novelData: [], // 存储接口返回的所有小说数据
    filteredData: [], // 筛选后的数据
    debounceTimer: null, // 防抖定时器
    currentKeyword: '', // 当前搜索关键词
    isLoading: false // 加载状态标识
};

// DOM 元素缓存（基于原始 HTML 结构）
const domElements = {
    searchInput: document.getElementById('searchInput'),
    searchBtn: document.getElementById('searchBtn'),
    // 动态创建结果容器（不修改原始 HTML，追加到搜索框下方）
    resultContainer: (() => {
        const container = document.createElement('div');
        container.id = 'searchResultContainer';
        container.style.cssText = `
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            margin-top: 8px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            z-index: 100;
            max-height: 400px;
            overflow-y: auto;
            display: none;
        `;
        // 将结果容器插入到搜索框父元素中
        document.querySelector('.search-content').appendChild(container);
        return container;
    })()
};

// 初始化：加载小说数据并绑定事件
async function initSearch() {
    // 优先加载接口数据
    await fetchNovelData();
    // 绑定交互事件
    bindSearchEvents();
}

// 调用小说接口获取数据
async function fetchNovelData() {
    try {
        const response = await fetch('https://www.iceread.com/api/common/rank/6273/0/1291');
        if (!response.ok) throw new Error('接口请求失败');
        
        const data = await response.json();
        // 提取小说核心数据（适配接口返回格式）
        searchState.novelData = data.list ? data.list.map(item => item.story || item) : [];
        searchState.filteredData = [...searchState.novelData];
    } catch (error) {
        console.error('小说数据加载失败:', error);
        renderResult(`<div style="padding:16px;text-align:center;color:#999;">数据加载失败，请稍后重试</div>`);
    }
}

// 绑定搜索相关事件
function bindSearchEvents() {
    // 搜索按钮点击
    domElements.searchBtn.addEventListener('click', handleSearch);
    
    // 输入框实时输入（防抖处理）
    domElements.searchInput.addEventListener('input', () => {
        searchState.currentKeyword = domElements.searchInput.value.trim().toLowerCase();
        
        // 清空关键词时隐藏结果容器
        if (!searchState.currentKeyword) {
            domElements.resultContainer.style.display = 'none';
            return;
        }
        
        // 防抖：300ms 内连续输入不触发搜索
        clearTimeout(searchState.debounceTimer);
        searchState.debounceTimer = setTimeout(handleSearch, 300);
    });
    
    // 回车键触发搜索
    domElements.searchInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') handleSearch();
    });
    
    // 点击页面其他区域隐藏结果容器
    document.addEventListener('click', (e) => {
        const isClickInside = domElements.searchInput.contains(e.target) || 
                             domElements.searchBtn.contains(e.target) || 
                             domElements.resultContainer.contains(e.target);
        if (!isClickInside) {
            domElements.resultContainer.style.display = 'none';
        }
    });
}

// 核心搜索逻辑
function handleSearch() {
    const keyword = searchState.currentKeyword;
    
    // 显示加载状态
    showLoading();
    
    // 筛选逻辑：匹配小说名、作者、标签
    searchState.filteredData = searchState.novelData.filter(novel => {
        const matchName = novel.name?.toLowerCase().includes(keyword) || false;
        const matchAuthor = novel.author?.toLowerCase().includes(keyword) || false;
        const matchTag = novel.tag?.toLowerCase().includes(keyword) || false;
        return matchName || matchAuthor || matchTag;
    });
    
    // 渲染搜索结果
    renderResult();
}

// 渲染搜索结果
function renderResult(customContent = '') {
    // 隐藏加载状态
    hideLoading();
    
    // 显示结果容器
    domElements.resultContainer.style.display = 'block';
    
    // 自定义内容渲染（如错误提示）
    if (customContent) {
        domElements.resultContainer.innerHTML = customContent;
        return;
    }
    
    // 无结果处理
    if (searchState.filteredData.length === 0) {
        domElements.resultContainer.innerHTML = `
            <div style="padding:24px;text-align:center;">
                <div style="font-size:24px;color:#ccc;margin-bottom:8px;">&#128270;</div>
                <p style="color:#666;">未找到包含「${searchState.currentKeyword}」的小说</p>
                <p style="color:#999;font-size:12px;margin-top:4px;">建议尝试其他关键词</p>
            </div>
        `;
        return;
    }
    
    // 渲染小说列表
    let resultHtml = '';
    searchState.filteredData.forEach(novel => {
        // 关键词高亮处理
        const highlight = (text) => {
            if (!text || !searchState.currentKeyword) return text;
            const regex = new RegExp(`(${searchState.currentKeyword})`, 'gi');
            return text.replace(regex, '<span style="color:#6366f1;font-weight:500;">$1</span>');
        };
        
        // 小说标签处理
        const tags = novel.tag ? novel.tag.split(',').slice(0, 2) : [];
        const tagHtml = tags.map(tag => `
            <span style="font-size:12px;padding:2px 6px;background:#f3f4f6;color:#666;border-radius:4px;margin-right:4px;">${highlight(tag)}</span>
        `).join('');
        
        // 单个小说项 HTML
        resultHtml += `
            <div style="padding:12px;border-bottom:1px solid #f5f5f5;cursor:pointer;" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background='transparent'" onclick='jumps(${JSON.stringify(novel)})'>
                <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:4px;">
                    <h4 style="margin:0;font-size:14px;color:#333;">${highlight(novel.name)}</h4>
                    ${novel.isPay === 1 ? '<span style="font-size:12px;color:#ef4444;background:#fee2e2;padding:1px 4px;border-radius:3px;">VIP</span>' : ''}
                </div>
                <p style="margin:0 0 6px 0;font-size:12px;color:#999;">作者：${highlight(novel.author)}</p>
                <div style="margin-bottom:6px;">${tagHtml}</div>
                <p style="margin:0;font-size:12px;color:#666;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                    ${highlight(novel.introduce ? novel.introduce.slice(0, 100) + '...' : '暂无简介')}
                </p>
            </div>
        `;
    });
    
    domElements.resultContainer.innerHTML = resultHtml;
}

// 显示加载状态
function showLoading() {
    searchState.isLoading = true;
    domElements.resultContainer.style.display = 'block';
    domElements.resultContainer.innerHTML = `
        <div style="padding:24px;text-align:center;">
            <div style="width:20px;height:20px;border:2px solid #6366f1;border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 8px;"></div>
            <p style="color:#666;font-size:12px;">正在搜索...</p>
        </div>
    `;
    // 添加加载动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
}

// 隐藏加载状态
function hideLoading() {
    searchState.isLoading = false;
}

// 页面加载完成后初始化搜索功能
document.addEventListener('DOMContentLoaded', initSearch);
function jumps(hearf){
       location.href=`./channelDetail.html?${JSON.stringify(hearf)}`
    }

// 实现推荐/打赏切换功能
function initRewardTabSwitch() {
    const tabBtns = document.querySelectorAll('.award .cutBtn-list'); 
    const recommendContent = document.querySelector('.award .cutRect-list');
    const rewardContent = document.querySelector('.award .cutRect-list1'); 

    if (tabBtns.length >= 2) {
        tabBtns[0].classList.add('on'); 
        tabBtns[1].classList.remove('on');
    }
    if (recommendContent && rewardContent) {
        recommendContent.style.display = 'block'; 
        rewardContent.style.display = 'none'; 
    }

    // 3. 给每个按钮绑定点击事件
    tabBtns.forEach((btn, index) => {
        btn.addEventListener('click', () => {
            tabBtns.forEach(item => item.classList.remove('on'));
            btn.classList.add('on');
            if (index === 0) {
                recommendContent.style.display = 'block';
                rewardContent.style.display = 'none';
            } else {
                recommendContent.style.display = 'none';
                rewardContent.style.display = 'block';
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', initRewardTabSwitch);

// const addbook=()=> {
//     console.log(bookData.cover);
//     console.log(bookData.latestChapter);
    
//     const bookimg = localStorage.setItem('bookimg',bookData.cover)
//     const bookzhangjie = localStorage.setItem('booklatestChapter',bookData.latestChapter)
//     const booktitle = localStorage.setItem('bookname',bookData.name)
// }
const addbook1 = document.querySelector('.addbook')
const addbook = () => {
   
  let savedBooks = localStorage.getItem('savedBooks');
  savedBooks = savedBooks ? JSON.parse(savedBooks) : [];
  const newBook = {
    cover: bookData.cover,
    latestChapter: bookData.latestChapter,
    name: bookData.name,
    finishTime:bookData.finishTime,
    id:bookData.id,
  }
  const isbookcunzai = savedBooks.some(book => book.id === newBook.id)

  if (!isbookcunzai) {
    savedBooks.push(newBook)
    localStorage.setItem('savedBooks', JSON.stringify(savedBooks))
  } else {
    console.log('书籍已存在');
  }
savedBooks = localStorage.getItem('savedBooks');
  savedBooks = savedBooks ? JSON.parse(savedBooks) : [];
  window.isbookcunzai = savedBooks.some(book => book.id === newBook.id); 
  m()
}